//
//  CommentListTableViewModel.m
//  YZZX
//
//  Created by Easaa on 15/4/28.
//  Copyright (c) 2015年 Easaa. All rights reserved.
//

#import "CommentListTableViewModel.h"

#import "CommentDataModel.h"//传过来的model
#import "CommentQuoteData.h"//tabviewl的model

#import "LFURlRequest.h"
#import "LFDataRequest.h"

#import "ContactModelCell.h"
#import "ContactvcCell.h"

@interface CommentListTableViewModel ()

/**
 *
 *  数据
 */
@property (nonatomic,strong) NSMutableArray *mtaDataArray;


@end

@implementation CommentListTableViewModel
{
    HXHttpRequest  *_httpRequest;
    NSMutableArray  *DataArry;

}


- (id)initWithFram:(CGRect)frame ObjectID:(NSDictionary *)objectDic
{
    self = [super initWithFrame:frame];
    if (self)
    {
        

        
        self.delegate = self;
        self.dataSource =self;
        DataArry = [[NSMutableArray alloc]init];
    
        CommentDataModel *CommentModelData = [[CommentDataModel alloc]initWithDataModel:objectDic];
        self.commModel = CommentModelData;
//        self.arryDta = [CommentModelData categoryListRequestWithObjectID:CommentModelData.id_massge];
        [self categoryListRequestWithObjectID:CommentModelData.id_massge];
        
        [self cateUIandDataModel];
        
        // 添加传统的下拉刷新
        __weak typeof(self) weakSelf = self;
        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
        [self addLegendHeaderWithRefreshingBlock:^{
            
            [weakSelf categoryListRequestWithObjectID:CommentModelData.id_massge];
            
            
        }];

    }
    return self;

}

#pragma mark 传入一个数组，构建UI
-(void)cateUIandDataModel
{

    
    //创建TableView 的TableHeadview
    UIView *HeadView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Dev_ScreenWidth, 80)];
    
    
    UILabel *lableTitles = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, Dev_ScreenWidth, 60)];
    lableTitles.font = [UIFont boldSystemFontOfSize:18.0f];  //UILabel的字体大小
    lableTitles.numberOfLines = 0;  //必须定义这个属性，否则UILabel不会换行
    lableTitles.textColor = RGBCOLOR(0, 0, 147);
    lableTitles.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
//[lableTitles setBackgroundColor:[UIColor redColor]];
    lableTitles.text =self.commModel.Title_massge;
    [HeadView addSubview:lableTitles];
    
    UILabel *lableTS = [[UILabel alloc]initWithFrame:CGRectMake(0, 60, Dev_ScreenWidth, 20)];
    lableTS.font = [UIFont boldSystemFontOfSize:14.0f];  //UILabel的字体大小
    lableTS.numberOfLines = 0;  //必须定义这个属性，否则UILabel不会换行
    lableTS.textColor = RGBCOLOR(0, 0, 147);
    lableTS.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    [lableTS setBackgroundColor:[UIColor grayColor]];
    lableTS.text =@"  最新评论";
    [HeadView addSubview:lableTS];
    self.tableHeaderView = HeadView;
}

#pragma mark 传入一个object_id请求跟帖数据，返回跟帖数据数组
-(void)categoryListRequestWithObjectID:(NSString *)object_id
{
    
     [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];

    //列表请求
    NSDictionary* dicParams = [NSDictionary dictionaryWithObjectsAndKeys:
                               [XSZ_UICommon useridChangUaerdfLoginBoolString],                                @"user_id",
                               @"1",                                @"site_id",
                               [NSNumber numberWithInteger:1],      @"page_no",
                               [NSNumber numberWithInteger:20],     @"page_size",
                               @"articles",                         @"app",
                               @"article",                          @"model",
                               object_id,                      @"object_id",
                               nil];
    
    
    if (_httpRequest == nil)
    {
        _httpRequest = [[HXHttpRequest alloc] init];
        _httpRequest.delegate = self;
        
        
        
    }
    [_httpRequest requestForParams:dicParams andMethod:YZ_COMMENT_LIST andTag:2001];//@"system.time"];//@"category.list"];
    
    
   
    

//    
//    //因要传入object_id，借用这个固定字段传入
//    
//    __block NSArray *arryData;
//    
//    NSURLRequest *urlRequest = [LFURlRequest getUrlRequestWithMethod:YZ_COMMENT_LIST
//                                                           andParams:@{@"user_id":      @"1",
//                                                                       @"site_id":      @"1",
//                                                                       @"page_no":      [NSNumber numberWithInteger:1],
//                                                                       @"page_size":    [NSNumber numberWithInteger:20],
//                                                                       @"app":          @"articles",
//                                                                       @"model":        @"article",
//                                                                       @"object_id":    object_id
//                                                                       }];
//    
//    [LFDataRequest dataRequestWith:urlRequest complete:^(id responseData, NSError *error) {
//        if (error)
//        {
//            
//        } else if (responseData)
//        {
//            if ([responseData isKindOfClass:[NSDictionary class]])
//            {
//                NSDictionary *dic = responseData;
//                if ([[dic objectForKey:@"is_success"] boolValue])
//                {
//                    NSString *strData = [dic objectForKey:@"data"];
//                    if (!StringIsEmpty(strData))
//                    {
//                      dispatch_main_async_safe(^{
//                    
//                        arryData = [JsonUtil jsonToArray:strData];
//                        
//                      });
//                        
//                    }
//                } else
//                {
//                    
//                    
//                }
//            }
//        }
//    }];
//    
//    return arryData;
}




#pragma mark - HXHttpRequestDelegate  代理

- (void)requestFinished:(NSString *)responseString andStatusCode:(int)statusCode andTag:(NSInteger)tag
{
    
    // 停止刷新状态
    [self.legendHeader endRefreshing];
    
    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
    
//    //停止刷新
//    [self.legendHeader endRefreshing];
//    [self.legendFooter endRefreshing];

   if(tag == 2001)
   {

        NSDictionary *dic = [[NSDictionary alloc]init];
        dic = [JsonUtil jsonToDic:responseString];
        
        if ([dic[@"data"] isEqual:[NSNull null]])
        {
            return;
        }
        
        NSString * strs = dic[@"data"];
        
        NSDictionary *dics =[JsonUtil jsonToDic:strs];
        
        NSArray *arryy =(NSArray *)dics;
        
        NSLog(@"-----------> %@",arryy);
        //NSMutableArray *arryData = [[NSMutableArray alloc]init];
       [DataArry removeAllObjects];
       
       NSArray *arrddd = [JsonUtil jsonToArray:strs];
       self.mtaDataArray = [NSMutableArray arrayWithArray:arrddd];
       
        for (NSDictionary *dicuu in arryy)
        {
 
            CommentQuoteData *cellmodel =[[CommentQuoteData alloc]init];
            cellmodel.comment = [dicuu objectForKey:@"comment"];
            cellmodel.id_massge = [dicuu objectForKey:@"id"];
            //cellmodel.quote= [dicuu objectForKey:@"quote"]; 这个为递归类型
            cellmodel.submit_date = [dicuu objectForKey:@"submit_date"];
            cellmodel.user_name= [dicuu objectForKey:@"user_name"];
     
           [DataArry addObject:cellmodel];
            
            
        }
    
        [self reloadData];
   }
    
        
 
}


#pragma mark  HXHttpRequest - 请求代理，，错误代理
- (void)requestFailed:(NSError *)error andTag:(NSInteger)tag
{
    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
    
    
    
    
    
}











#pragma arguments - mark  UITableViewDelegate
// 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return self.mtaDataArray.count;
    return DataArry.count;
}


//设置每行高度（每行高度可以不一样）
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    NSDictionary *dic = self.mtaDataArray[indexPath.row];
//    CGFloat hhh = [ContactModelCell heightOfCommentWithAttributes:dic withLastHeight:0 lastWidth:320];
//    
//    return hhh + 15;
    
    NSDictionary *dic = self.mtaDataArray[indexPath.row];
    CGFloat hhh = [ContactvcCell heightOfCommentWithAttributes:dic withLastHeight:0 lastWidth:320];
    
    return hhh ;

    
    
    
    
    
    
    
//    
//    //判断Cell类型
//    Cellcellmodel = [DataModel objectAtIndex:indexPath.row];
//    if([Cellcellmodel.Image isEqual:[NSNull null]]&&Cellcellmodel.Summary.length<=0)
//        
//    {
//        
//        return 44;
//        
//    }else if ([Cellcellmodel.Image isEqual:[NSNull null]]&&Cellcellmodel.Summary.length>0) {
//        
//        // ModelTwoTableViewCell
//        
//        
//        return 80;
//    }
    
     CommentQuoteData *cellmodel = [DataArry objectAtIndex:indexPath.row];
    
//     (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context 
    
    CGSize size = [cellmodel.comment sizeWithFont:[UIFont boldSystemFontOfSize:12] constrainedToSize:CGSizeMake(Dev_ScreenWidth-20, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
    
    NSInteger higeh;
    if(size.height>40)
    {
        higeh = size.height-40+60;
    }else if (size.height<=40)
    {
        higeh = 60;
        
    }
    
    return higeh+10;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static  NSString  *CellIdentiferId = @"ContactModelCellID";
    
    
    
//    
//    ContactModelCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentiferId];
//    if (!cell){
//        cell = [[ContactModelCell alloc] initWithDataStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentiferId];
//    }
//    
//    
//    //FIXME:修复无限盖楼
//    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
//    [cell configureCellWithAttributes:self.mtaDataArray[indexPath.row]];
//    
//    [cell tapCommentViewWithBlock:^(NSDictionary *att) {
//       
//        [self handleTapCommentViewWith:att];
//    }];
    
    
    
    ContactvcCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentiferId];
    if (!cell){
        cell = [[ContactvcCell alloc] initWithDataStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentiferId];
    }
    
    cell.tableview  = self;
    cell.id_massge = self.commModel.id_massge;
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [cell configureCellWithAttributes:self.mtaDataArray[indexPath.row]];

    

    
    return cell;
}

- (void)handleTapCommentViewWith:(NSDictionary *)att
{
    NSLog(@"%@",att[@"id"]);

}

#pragma mark   Tableview  点击事件代理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    MassgeViewModelVC  *massgeview = [[MassgeViewModelVC alloc]initWithEstablish:[DataModel objectAtIndex:indexPath.row]];
//    [self.ListTableviewdelegate PushViewContorller:massgeview DataModel: [DataModel objectAtIndex:indexPath.row]];
    
    
    
}



@end


